﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BySoft.Server.Business;
using BySoft.Web.Utility;
using BySoft.Server.Common.Entity;
using BySoft.Server.Common;
using OneSoft.EntityCore;
using BySoft.Server.Common.Enum;
using BySoft.Server.Consts;

namespace BySoft.Web.Site.MasteData
{
    public partial class CustomerAdd : AuthBasePage
    {
       

        #region 属性定义
        private string m_strsequenceName
        {
            get
            {
                return "MD_Customer";
            }
        }
        private string m_strTbl = "MD_Customer";
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CustomerDetailDT = null;
                BindDDL();
                DataInfo();
            }
            Master.ValidationGroup = "gSubmit";
        }
        private void BindDDL()
        {
            BindParameterForListControl("CustomerFrom", ddlCustomerFrom);
            UIHelper.InsertFirstItem(ddlCustomerFrom);

            BindParameterForListControl("CustomerScaler", ddlCustomerScaler);
            UIHelper.InsertFirstItem(ddlCustomerScaler);
        }

        private DataTable CreateDT()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("CustomerDetailID");
            dt.Columns.Add("CustomerID");
            dt.Columns.Add("ContactName");
            dt.Columns.Add("Tel");
            dt.Columns.Add("Job");
            dt.Columns.Add("Mobile");
            dt.Columns.Add("Email");
            dt.Columns.Add("QQ");
            return dt;
        }
        public DataTable CustomerDetailDT
        {
            get
            {
                if (Session["CustomerDetailDT"] != null)
                {
                    return (DataTable)Session["CustomerDetailDT"];
                }
                else
                {
                    return CreateDT();
                }
            }
            set
            {
                Session["CustomerDetailDT"] = value;
            }
        }

        private void DataInfo()
        {
            this.lblCustomerID.Text = ClsComm.GetMaxSequenceID(m_strsequenceName, "KH", 7);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(CurrentUser.UserID))
                {
                    UIHelper.AlertMessage(this.Page, "等待时间太久，请重新填写客户资料！");
                    return;
                }
                if (!string.IsNullOrEmpty(this.lblCustomerID.Text.Trim()))
                {
                    string customerName = this.txtCustomerName.Text.Trim();
                    if (!string.IsNullOrEmpty(customerName))
                    {
                        if (MdCustomer.IsCustomerNameExists(customerName))
                        {
                            UIHelper.AlertMessage(this.Page, "客户名称已存在，请重新填写！");
                            return;
                        }
                    }
                    //创建客户
                    MdCustomerEntity entity = new MdCustomerEntity();
                    entity.CustomerName = customerName;
                    entity.CustomerScaler = this.ddlCustomerScaler.SelectedValue.Trim();
                    entity.CustomerFrom = this.ddlCustomerFrom.SelectedValue.Trim();
                    entity.CustomerID = this.lblCustomerID.Text.Trim();
                    entity.Addr = this.txtAddr.Text.Trim();
                    entity.MasterPerson = this.txtMasterPerson.Text.Trim();
                    entity.Status = "1";
                    entity.CreateDate = DateTime.Now;
                    entity.CreateUserID = CurrentUser.UserID;
                    entity.CreateUserName = CurrentUser.UserName;
                    
                    List<MdCustomerdetailEntity> list = new List<MdCustomerdetailEntity>();
                    foreach (GridViewRow gvr in this.grdDetail.Rows)
                    {
                        TextBox txtContactName = gvr.FindControl("txtContactName") as TextBox;
                        TextBox txtJob = gvr.FindControl("txtJob") as TextBox;
                        TextBox txtTel = gvr.FindControl("txtTel") as TextBox;
                        TextBox txtMobile = gvr.FindControl("txtMobile") as TextBox;
                        TextBox txtEmail = gvr.FindControl("txtEmail") as TextBox;
                        TextBox txtQQ = gvr.FindControl("txtQQ") as TextBox;

                        MdCustomerdetailEntity detail = new MdCustomerdetailEntity();
                        detail.CustomerID = entity.CustomerID;
                        detail.ContactName = txtContactName.Text.Trim();
                        detail.Job = txtJob.Text.Trim();
                        detail.Tel = txtTel.Text.Trim();
                        detail.Mobile = txtMobile.Text.Trim();
                        detail.Email = txtEmail.Text.Trim();
                        detail.QQ = txtQQ.Text.Trim();
                        list.Add(detail);
                    }
                    if (list.Count < 1)
                    {
                        UIHelper.AlertMessage(this.UpdatePanel4, "请添加明细！");
                        return;
                    }
                    if (MdCustomer.Save(entity))
                    {
                        ClsComm.SetMaxSequenceID(m_strsequenceName);
                        MdCustomerdetail.Save(list);
                        base.LogAction(BaseEnum.ActionType.Add, entity.CustomerID, true, null, new EntityBase[] { entity });
                        UIHelper.AlertMessageGoToURL(this.Page, Message.SaveSuccess, "../MasteData/CustomerList.aspx");
                    }
                    else
                    {
                        UIHelper.AlertMessage(this.Page, Message.SaveFail);
                    }
                }
            }
            catch (Exception ex)
            {
                UIHelper.AlertMessage(this.Page, FomatString(ex.Message.ToString()));
            }
        }

        decimal dTryDecimal(object objet, decimal dNullData)
        {
            decimal dReturn = dNullData;
            try { dReturn = Convert.ToDecimal(CommonMethod.GetString(objet)); }
            catch { }
            return dReturn;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            GetGridViewData();
            DataTable dt = CustomerDetailDT.Copy();
            DataRow row = dt.NewRow();
            row["CustomerDetailID"] = -1;
            dt.Rows.Add(row);

            CustomerDetailDT = dt;
            BindData();
        }

        private void GetGridViewData()
        {
            DataTable dttemp = CreateDT();
            foreach (GridViewRow gvr in grdDetail.Rows)
            {
                TextBox txtContactName = gvr.FindControl("txtContactName") as TextBox;
                TextBox txtTel = gvr.FindControl("txtTel") as TextBox;
                TextBox txtJob = gvr.FindControl("txtJob") as TextBox;
                TextBox txtMobile = gvr.FindControl("txtMobile") as TextBox;
                TextBox txtEmail = gvr.FindControl("txtEmail") as TextBox;
                TextBox txtQQ = gvr.FindControl("txtQQ") as TextBox;


                DataRow row = dttemp.NewRow();
                row["ContactName"] = GetGridViewString(txtContactName);
                row["Tel"] = GetGridViewString(txtTel);
                row["Job"] = GetGridViewString(txtJob);
                row["Mobile"] = GetGridViewString(txtMobile);
                row["Email"] = GetGridViewString(txtEmail);
                row["QQ"] = GetGridViewString(txtQQ);


                dttemp.Rows.Add(row);
            }
            dttemp.AcceptChanges();
            CustomerDetailDT = dttemp;
        }


        private void BindData()
        {
            if (CustomerDetailDT.Rows.Count > 0)
            {
                this.grdDetail.DataSource = CustomerDetailDT;
                grdDetail.DataBind();
                SetControlAttr(new MdCustomerdetailEntity(), grdDetail);
            }
            else
            {
                UIHelper.BindEmptyGridView(grdDetail, CreateDT());
            }
            UIHelper.RunScript(this.Page, "iframeAutoFit();");
        }
        protected void grdDetail_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string name = e.CommandName;
            if (name == "del")
            {
                GetGridViewData();
                string str = e.CommandArgument.ToString();
                int iDel = CommonMethod.ConvertToInt(str);
                DataTable dt = CustomerDetailDT.Copy();
                dt.Rows.RemoveAt(iDel);
                CustomerDetailDT = dt.Copy();
                BindData();
                UIHelper.AlertMessage(this.Page, Message.DeleteSuccess);
            }
        }

        protected void grdDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                #region 删除绑定
                ImageButton ibtn = (ImageButton)e.Row.FindControl("ibtnDel");
                Button btnDel = (Button)e.Row.FindControl("btnDel");
                if (ibtn != null)
                {
                    ibtn.OnClientClick = "ShowTopConfirm('提示信息','" + Message.ConfirmDelete + "','confirmCallback(\\'" + btnDel.ClientID + "\\')');return false;";
                }
                #endregion
            }
        }
    }
}